import { electronAPI } from "@electron-toolkit/preload";
import { initPreloadBridge } from "@main/bridge";
import logger from "@shared/logger/main-logger";
import { contextBridge, ipcRenderer, webUtils } from "electron";

const api = {
  platform: process.platform,
  webUtils: {
    getPathForFile: webUtils.getPathForFile,
  },
  // Direct shell access for emergency situations (like splash screen)
  shell: {
    openLogDirectory: async (): Promise<{
      success: boolean;
      error?: string;
    }> => {
      try {
        // Use ipcRenderer to call a direct shell method in main process
        const result = await ipcRenderer.invoke("shell:openLogDirectory");
        return result;
      } catch (error) {
        logger.error("Direct shell API: Error opening log directory", {
          error,
        });
        return {
          success: false,
          error: error instanceof Error ? error.message : "Unknown error",
        };
      }
    },
  },
};

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld("electron", electronAPI);
    contextBridge.exposeInMainWorld("api", api);
    contextBridge.exposeInMainWorld("service", initPreloadBridge());
  } catch (error) {
    logger.error("Preload: Error exposing services", { error });
  }
} else {
  // @ts-expect-error (define in dts)
  window.electron = electronAPI;
  // @ts-expect-error (define in dts)
  window.api = api;
}

export type WindowApiType = typeof api;
